<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <a-form size="small" :model="queryData" layout="inline">
          <a-form-item label="客户">
            <a-input
              :style="{ width: '200px' }"
              class="bacClass"
              v-model="queryData.client"
              allow-clear
              @press-enter="enter"
            />
          </a-form-item>
        </a-form>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar
          :items="['查询', '新增', '删除']"
          @add="addHandler"
          @del="deleteHandler"
          @select="selectHandler"
        >
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 100%"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
        :suppressRowClickSelection="true"
      ></AgGridVuesCopys>
    </template>

    <paginationCopys
      :page-size="pagination.pageSize"
      :current="pagination.page"
      :total="pagination.total"
      show-total
      show-jumper
      show-page-size
      @change="nextDoRefreshPage"
      @page-size-change="nextDoRefreshSize"
      style="justify-content: center"
    />

    <a-drawer
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="500"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      :ok-loading="saveLoading"
      @cancel="pageData.showAdd = false"
      cancel-text="关闭"
      ok-text="保存"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" :model="dataForm" layout="horizontal">
          <a-form-item
            label-col-flex="120px"
            label="客户"
            field="client"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '客户必填' }]"
          >
            <a-input class="bacClass" v-model="dataForm.client" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="测试类型"
            field="testType"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '测试类型必填' }]"
          >
            <a-input class="bacClass" v-model="dataForm.testType" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="面料测试项目"
            field="liningItem"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '面料测试项目必填' }]"
          >
            <a-input class="bacClass" v-model="dataForm.liningItem" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="测试标准"
            field="testStandard"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '客户必填' }]"
          >
            <a-input class="bacClass" v-model="dataForm.testStandard" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="测试方法"
            field="testMethod"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '测试方法必填' }]"
          >
            <a-input class="bacClass" v-model="dataForm.testMethod" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="面料测试要求"
            field="testRrequire"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '面料测试要求必填' }]"
          >
            <a-input class="bacClass" v-model="dataForm.testRrequire" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="面料测试大类"
            field="liningHeading"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '面料测试大类必填' }]"
          >
            <a-input class="bacClass" v-model="dataForm.liningHeading" />
          </a-form-item>
          <a-form-item label-col-flex="120px" label="备注" field="remark">
            <a-textarea class="bacClass" v-model="dataForm.remark" allow-clear />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>
<script lang="ts">
  import { post, get } from '@/api/http'
  import { useTable, usePagination, useTableColumn } from '@/hooks/table'
  import { ref, reactive, onMounted } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import 'ag-grid-community/styles/ag-grid.css'
  import 'ag-grid-community/styles/ag-theme-alpine.css'
  import { localeText } from '@/api/aggridZw'
  
  interface paramData {
    id: any
    client: string | undefined
    testType: string | undefined
    testStandard: string | undefined
    liningItem: string | undefined
    testMethod: string | undefined
    testRrequire: string | undefined
    liningHeading: string | undefined
    remark: string | undefined
  }
  export default {
    //客户测试项目
    name: 'CustomerTestItems',
    setup() {
      //隐藏显示头部
      const headerShow = ref<boolean>(true)
      //抽屉保存按钮加载状态
      const saveLoading = ref<boolean>(false)
      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        pageLoading: boolean
        theight: number
        rHeight: number | undefined
      }>({
        showAdd: false,
        sideTitle: '新增客户测试项目',
        dropDownData: '',
        pageLoading: false,
        theight: 0,
        rHeight: 0,
      })
      //查询列表
      onMounted(() => {
        selectHandler()
      })
      //切换分页
      const nextDoRefreshPage = (val: any) => {
        pagination.page = val
        doRefresh()
      }
      const nextDoRefreshSize = (val: any) => {
        pagination.pageSize = val
        doRefresh()
      }
      const pagination = usePagination(doRefresh)
      const table = useTable()
      function doRefresh() {
        pageData.pageLoading = true
        post({
          url: 'dwQms/ClientTest/getPage',
          data: {
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,
            client: queryData.client,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.data)
              pagination.setTotalSize(data.total)
              gridOption.value.setRowData(data.data)
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      //查询
      const selectHandler = () => {
        pagination.page = 1
        doRefresh()
      }
      //------新增、修改页面开始------
      const dataForm = reactive<paramData>({
        id: null,
        client: '',
        testType: '',
        liningItem: '',
        testStandard: '',
        testMethod: '',
        testRrequire: '',
        liningHeading: '',
        remark: '',
      })
      const addHandler = () => {
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else {
            dataForm[key] = ''
          }
        }
        pageData.showAdd = true
        pageData.sideTitle = '新增客户测试项目'
      }
      const editHandler = (record: paramData) => {
        for (var key in record) {
          dataForm[key] = record[key]
        }
        pageData.sideTitle = '修改客户测试项目'
        pageData.showAdd = true
      }

      const formRef = ref<FormInstance>()
      const sideOk = () => {
        saveLoading.value = true
        formRef.value?.validate().then((err) => {
          if (!err) {
            if (pageData.sideTitle === '新增客户测试项目') {
              post({
                url: 'dwQms/ClientTest/insert',
                data: [dataForm],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  saveLoading.value = false
                })
            } else {
              post({
                url: 'dwQms/ClientTest/update',
                data: [dataForm],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  saveLoading.value = false
                })
            }
          } else {
            saveLoading.value = false
          }
        })
      }
      //------新增、修改页面结束------
      //------删除方法开始------
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            post({
              url: 'dwQms/ClientTest/delete',
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            }).then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })

                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '删除失败',
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      //------删除方法结束------
      const enter = () => {
        doRefresh()
      }

      const queryData = reactive({
        client: '',
      })

      // 表格准备事件
      const tableColumns = useTableColumn([
        {
          title: '序号',
          key: 'serialNumber',
          dataIndex: 'serialNumber',
          width: 150,
        },
        {
          title: '客户',
          key: 'client',
          dataIndex: 'client',
          width: 150,
        },
        {
          title: '测试类型',
          key: 'testType',
          dataIndex: 'testType',
          width: 150,
        },
        {
          title: '面料测试项目',
          key: 'liningItem',
          dataIndex: 'liningItem',
          width: 150,
        },
        {
          title: '测试标准',
          key: 'testStandard',
          dataIndex: 'testStandard',
          width: 150,
        },
        {
          title: '测试方法',
          key: 'testMethod',
          dataIndex: 'testMethod',
          width: 150,
        },
        {
          title: '面料测试要求',
          key: 'testRrequire',
          dataIndex: 'testRrequire',
          width: 150,
        },
        {
          title: '面料测试大类',
          key: 'liningHeading',
          dataIndex: 'liningHeading',
          width: 150,
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
        },

        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
        },

        {
          title: '操作',
          key: 'id',
          dataIndex: 'id',
          slotName: 'act',
          width: 150,
          fixed: 'right',
        },
      ])
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          width: o.width,
        }
        if (o.slotName === 'act') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = o.fixed
          obj['cellRenderer'] = {
            template: `<el-button style="color:#165dff;" link @click="a">修改</el-button>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                a,
              }
            },
          }
        }
        console.log(obj)
        return obj
      })
      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const localeText1: any = ref(localeText)
      return {
        deleteHandler,
        saveLoading,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        pagination,
        table,
        pageData,
        editHandler,
        selectHandler,
        headerShow,
        queryData,
        nextDoRefreshPage,
        nextDoRefreshSize,
        enter,
        defaultColDef,
        localeText1,
        tc,
        gridReady,
        gridOption,
      }
    },
    components: { Toolbar,  },
  }
</script>
<style scoped lang="less">
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
</style>
